package com.seveneight.baijiesteward.ui.main.fragment;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseFragment;
import com.seveneight.baijiesteward.adapter.ShareAdapter;
import com.seveneight.baijiesteward.bean.ShareImgBean;
import com.seveneight.baijiesteward.bean.UserBean;
import com.seveneight.baijiesteward.http.AppConfig;
import com.seveneight.baijiesteward.http.HttpConfig;
import com.seveneight.baijiesteward.ui.main.activity.LoginActivity;
import com.seveneight.baijiesteward.ui.main.contract.ShareImgContract;
import com.seveneight.baijiesteward.ui.main.presenter.ShareImgPresenter;
import com.seveneight.baijiesteward.ui.share.activity.ShareActivity;
import com.seveneight.baijiesteward.utils.GetBitmapUtil;
import com.seveneight.baijiesteward.utils.GlideLoader;
import com.seveneight.baijiesteward.utils.ImageUtils;
import com.seveneight.baijiesteward.utils.LogUtil;
import com.seveneight.baijiesteward.utils.ToastUtil;
import com.seveneight.baijiesteward.utils.WaterMaskUtil;
import com.seveneight.baijiesteward.utils.WindowUtil;
import com.seveneight.baijiesteward.views.cover.FancyCoverFlow;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

/**
 * Created by user1 on 2018/2/6.
 */

public class ShareFragment extends BaseFragment implements ShareImgContract.ShareImgView, View.OnClickListener {

    ShareImgContract.ShareImgPresenter shareImgPresenter;
    private FancyCoverFlow fcf_share;
    private ImageView iv_bigimg;
    private ShareAdapter adapter;
    private List<ShareImgBean> data;
    private TextView tv_next;
    private int posi = 0;
    private Bitmap bitmap;
    private Bitmap shareBitmap;
    private Bitmap finallyBitmap;

    @Override
    protected int getContentView() {
        return R.layout.fragment_share;
    }

    public static ShareFragment newInstance() {
        Bundle args = new Bundle();
        ShareFragment fragment = new ShareFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        tv_next = findView(R.id.tv_next);
        iv_bigimg = findView(R.id.iv_bigimg);
        fcf_share = findView(R.id.fcf_share);
        fcf_share.setUnselectedSaturation(0.4f);
        fcf_share.setMaxRotation(0);
        fcf_share.setUnselectedScale(1.0f);
        fcf_share.setUnselectedAlpha(0.3f);
        fcf_share.setSpacing(-80);
        fcf_share.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
    }

    @Override
    protected void initData() {
        shareImgPresenter = new ShareImgPresenter(this);
        shareImgPresenter.getImgData(mContext, jsonFormat.commonParam());
    }

    @Override
    protected void setListener() {
        tv_next.setOnClickListener(this);
        fcf_share.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                posi = position;
                GlideLoader.displayImg(mContext, HttpConfig.SOURCE_URL + data.get(position).getBgUrl(), iv_bigimg);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void reBackData(List<ShareImgBean> data) {
        this.data = data;
        adapter = new ShareAdapter(mContext, data);
        fcf_share.setAdapter(adapter);
        fcf_share.setSelection(1, false);
    }

    @Override
    public void onClick(View view) {
        if (!setting.isLogin()) {
            WindowUtil.getInstance().startUpActivity(getActivity(), LoginActivity.class);
            return;
        }
        switch (view.getId()) {
            case R.id.tv_next:
                createBitmap();
                break;
        }
    }

    private void createBitmap() {
        showLoading("正在压缩图片...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 这里进行下载操作...获得了图片的bitmap
                    Bitmap bitmap = GetBitmapUtil.getBitmap(HttpConfig.SOURCE_URL + data.get(posi).getBgUrl());
                    //下载完后才，向主线程发送Message
                    Message msg = Message.obtain();
                    msg.obj = bitmap;
                    msg.what = 1;//区分哪一个线程发送的消息
                    mHadler.sendMessage(msg);
                } catch (IOException ex) {

                }
            }
        }).start();
    }

    private void createQrcodeBitmap() {
        showLoading("正在生成个人二维码...");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    // 这里进行下载操作...获得了图片的bitmap
//                    UserBean userBean = setting.getUserInfo();
                    if (userBean==null){
                        userBean = setting.getUserInfo();
                    }
                    Resources resources = mContext.getResources();
                    DisplayMetrics dm = resources.getDisplayMetrics();
                    float density = dm.density;
                    int width = dm.widthPixels;
                    int screenWidth = width * (int) density;
                    int multiple = screenWidth / 1000;
                    LogUtil.d("multiple", multiple + "");
                    int flag = 0;
                    if (multiple <= 1) {
                        flag = 95;
                    } else {
                        flag = 55;
                    }
                    Bitmap qrBitmap = QRCodeEncoder.syncEncodeQRCode(AppConfig.REGISTER + userBean.getMobilePhone(), data.get(posi).getBarCode_Height(), Color.parseColor("#000000"));
//                    Bitmap qrBitmap = QRCodeEncoder.syncEncodeQRCode(AppConfig.REGISTER + userBean.getMobilePhone(), BGAQRCodeUtil.dp2px(mContext, data.get(posi).getBarCode_Height()/2), Color.parseColor("#000000"));
                    //下载完后才，向主线程发送Message
                    Message msg = Message.obtain();
                    msg.obj = qrBitmap;
                    msg.what = 2;//区分哪一个线程发送的消息
                    mHadler.sendMessage(msg);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }, 1000);
    }

    private void createShareBitmap() {
        showLoading("正在合成分享图片...");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    // 这里进行下载操作...获得了图片的bitmap
                    Bitmap finallyBitmap = ImageUtils.createWaterMaskRightTop(mContext, bitmap, shareBitmap, data.get(posi).getBarCode_X(), data.get(posi).getBarCode_Y());
                    //下载完后才，向主线程发送Message
                    Message msg = Message.obtain();
                    msg.obj = finallyBitmap;
                    msg.what = 3;//区分哪一个线程发送的消息
                    mHadler.sendMessage(msg);
                } catch (Exception ex) {

                }
            }
        }, 1000);
    }

    Handler mHadler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    hideLoading();
                    bitmap = (Bitmap) msg.obj;
                    if (bitmap != null) {
                        createQrcodeBitmap();
                    } else {
                        showDialog("压缩失败，请重新尝试");
                    }
                    break;
                case 2:
                    hideLoading();
                    shareBitmap = (Bitmap) msg.obj;
                    if (shareBitmap != null) {
                        createShareBitmap();
                    } else {
                        showDialog("生成二维码失败，请重新尝试");
                    }
                    break;
                case 3:
                    hideLoading();
                    finallyBitmap = (Bitmap) msg.obj;
                    if (finallyBitmap != null) {
                        String path = GetBitmapUtil.saveImageToGallery(mContext, finallyBitmap);
                        Bundle bundle = new Bundle();
                        bundle.putString("path", path);
                        WindowUtil.getInstance().startActivity(getActivity(), ShareActivity.class, bundle);
                    } else {
                        showDialog("合成图片失败，请重新尝试");
                    }

                    break;
            }
        }
    };
}
